package net.myspring.common.mybatis.interceptor;

/**
 * Created by liuj on 2016/11/16.
 */

import net.myspring.common.mybatis.provider.ProviderUtils;
import net.myspring.common.mybatis.provider.annotation.Entity;
import net.myspring.common.mybatis.provider.annotation.GenerationType;
import net.myspring.common.mybatis.provider.model.MybatisTable;
import net.myspring.common.utils.ReflectionUtils;
import net.myspring.common.utils.SnowflakeUtils;
import net.myspring.common.utils.ThreadLocalContext;
import net.myspring.middle.domain.Account;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.data.annotation.LastModifiedBy;
import org.springframework.data.annotation.LastModifiedDate;

import java.lang.reflect.Field;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;

/**
 * 审计接口，自动注入用户id以及自动获取注入更新时间和创建时间
 */
@Intercepts({@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})})
public class MybatisAuditingInterceptor implements Interceptor {
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
        SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();
        Object parameter = invocation.getArgs()[1];
        if (parameter != null) {
            if (parameter.getClass().getAnnotation(Entity.class) != null) {
                MybatisTable mybatisTable = ProviderUtils.getMybatisTable(parameter.getClass());
                setFieldValue(mybatisTable, parameter, sqlCommandType);
            } else {
                if (Map.class.isAssignableFrom(parameter.getClass())) {
                    if(((Map) parameter).containsKey("list")) {
                        List<Object> list = (List<Object>) ((Map) parameter).get("list");
                        for (Object entity :list) {
                            if (entity.getClass().getAnnotation(Entity.class) != null) {
                                MybatisTable mybatisTable = ProviderUtils.getMybatisTable(entity.getClass());
                                setFieldValue(mybatisTable, entity, sqlCommandType);
                            }
                        }
                    }
                }
            }
        }
        return invocation.proceed();
    }

    @Override
    public Object plugin(Object target) {
        if (target instanceof Executor) {
            return Plugin.wrap(target, this);
        } else {
            return target;
        }
    }

    @Override
    public void setProperties(Properties properties) {

    }

    private void setFieldValue(MybatisTable mybatisTable, Object entity, SqlCommandType sqlCommandType) {
        if (SqlCommandType.UPDATE == sqlCommandType || SqlCommandType.INSERT == sqlCommandType) {
            Account account = ThreadLocalContext.get().getAccount();
            LocalDateTime localDateTime = LocalDateTime.now();
            if (SqlCommandType.INSERT == sqlCommandType) {
                if (mybatisTable.getId() != null) {
                    if (GenerationType.SNOWFLAKE.name().equals(mybatisTable.getGenerationType())) {
                        ReflectionUtils.setFieldValue(entity, mybatisTable.getId().getFieldName(), SnowflakeUtils.getId());
                    } else if (GenerationType.UUID.name().equals(mybatisTable.getGenerationType())) {
                        ReflectionUtils.setFieldValue(entity, mybatisTable.getId().getFieldName(), UUID.randomUUID().toString());
                    }
                }
                if (mybatisTable.getCreatedBy() != null) {
                    ReflectionUtils.setFieldValue(entity, mybatisTable.getCreatedBy().getFieldName(), account == null ? null : account.getId());
                }
                if (mybatisTable.getCreatedDate() != null) {
                    ReflectionUtils.setFieldValue(entity, mybatisTable.getCreatedDate().getFieldName(), localDateTime);
                }
                if (mybatisTable.getVersion() != null) {
                    ReflectionUtils.setFieldValue(entity, mybatisTable.getVersion().getFieldName(), 0L);
                }
            }
            if (mybatisTable.getLastModifiedBy() != null) {
                ReflectionUtils.setFieldValue(entity, mybatisTable.getLastModifiedBy().getFieldName(), account == null ? null : account.getId());
            }
            if (mybatisTable.getLastModifiedDate() != null) {
                ReflectionUtils.setFieldValue(entity, mybatisTable.getLastModifiedDate().getFieldName(), localDateTime);
            }
        }
    }
}